package com.learn.project2.config.typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @description:
 * @author 岳子昂
 * @date 2022-01-08 00:45
 * @version 1.0
 */
@MappedTypes(Boolean.class)
@MappedJdbcTypes(JdbcType.TINYINT)
public class Boolean2IntegerTypeHandler implements TypeHandler<Boolean> {

    // jackson
    ObjectMapper objectMapper = new ObjectMapper();

    // boolean - int
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Boolean aBoolean, JdbcType jdbcType) throws SQLException {
        if (aBoolean){
            preparedStatement.setInt(i,1);
        }else {
            preparedStatement.setInt(i,0);
        }
    }

    // int - boolean
    @Override
    public Boolean getResult(ResultSet resultSet, String s) throws SQLException {
        int anInt = resultSet.getInt(s);
        if (anInt == 1){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public Boolean getResult(ResultSet resultSet, int i) throws SQLException {
        int anInt = resultSet.getInt(i);
        if (anInt == 1){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public Boolean getResult(CallableStatement callableStatement, int i) throws SQLException {
        int anInt = callableStatement.getInt(i);
        if (anInt == 1){
            return true;
        }else {
            return false;
        }
    }
}
